package com.controllers
{
	import com.data.CSVParser;
	import com.data.FilterData;
	import com.data.GenData;
	import com.data.GenIdFilterData;
	
	import flash.filesystem.File;
	
	import mx.collections.ArrayCollection;
	
	[Bindable]
	public class GenManager
	{
		
		public var gens:Array = new Array();
		public var scoreNames:Array;
		public var filtersData:ArrayCollection = new ArrayCollection();

		[Embed(source="assets/progress.csv", mimeType="application/octet-stream")]
		private var FileClass : Class;
		private var obj:Object = new FileClass();

		
		public function GenManager(progressFile:String)
		{
			var csvParser:CSVParser = new CSVParser();
			//var csvParser:CSVParser = new CSVParser(File.documentsDirectory.resolvePath(progressFile));
			//var items:Array = csvParser.parseFile(new File(progressFile));
			
			var items:Array = csvParser.parseString(obj.toString());
			
			scoreNames = ["daylight", "energy", "cost"];
			var attrs:Array = csvParser.attrs;
			
			trace("The no of gens " + items.length);
			
			var id:int = 1;
			for each(var item:Object in items)
			{
				for (var i:int = 0; i < 3; i++)
				{
					var gen:GenData = new GenData();
					gen.genId = id;
					gen.scoreName = scoreNames[i];
					gen.min = item[attrs[i*3+1]];
					gen.avg = item[attrs[i*3+2]];
					gen.max = item[attrs[i*3+3]];
					//trace(gen.toString());
					gens.push(gen);
				}
				id++;
			}
			
			setFilterData();
			updateFilterMinMax();
		}
		
		private function setFilterData():void
		{
			filtersData.addItem(new GenIdFilterData("genId", "Generation Id"));				
		}
		
		private function updateFilterMinMax():void
		{
			if (gens.length == 0) return;
			for (var i:int = 0; i < filtersData.length; i++)
			{
				var filterData:FilterData = filtersData[i];
				var fname:String = filterData.fieldName;
				filterData.minVal = gens[0][fname];
				filterData.maxVal = gens[0][fname];
				
				for each(var genData:GenData in gens)
				{
					if (genData[fname] < filterData.minVal)
						filterData.minVal = genData[fname];
					if (genData[fname] > filterData.maxVal)
						filterData.maxVal = genData[fname];
				}
			}
		}
		
		public function allGens():ArrayCollection
		{
			return new ArrayCollection(gens);
		}
		
		public function filterGens(scoreName:String):ArrayCollection
		{
			var ret:ArrayCollection = new ArrayCollection();
			for each(var gen:GenData in gens)
			{
				var isOk:Boolean = true;
				if (gen.scoreName != scoreName) 
					continue;
				for each(var filterData:GenIdFilterData in filtersData)
					if(filterData.isOk(gen) == false)
					{
						isOk = false;
						break;
					}
				if (isOk)
					ret.addItem(gen);
			}
			return ret;
		}
	}
}